<template>
  <div>
    <el-form style="margin: 10px 0" :model="queryForm" inline>
      <el-form-item label="用户名">
        <el-input
          suffix-icon="el-icon-position"
          style="width: 200px"
          v-model="queryForm.username"
          placeholder="请输入用户名"
        ></el-input>
      </el-form-item>
      <el-form-item label="帖子标题">
        <el-input
          suffix-icon="el-icon-position"
          style="width: 200px"
          v-model="queryForm.title"
          placeholder="请输入帖子标题"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button class="mll-5" type="primary" @click="fetchPost"
          >查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button class="mll-5" type="warning" @click="reset">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          class="mll-5"
          type="danger"
          @click="deleteSelected"
          :disabled="!this.selectedIds.length"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>

    <el-card class="box-card">
      <el-table
        :data="postList"
        script
        style="width: 100%"
        @selection-change="handelSelectionChange"
        :row-key="(row) => row.id"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column prop="id" label="帖子id" align="center" />
        <el-table-column prop="title" label="标题" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="playCount" label="游玩次数" align="center" />
        <el-table-column prop="createdTime" label="创建时间" align="center">
          <template slot-scope="scope">
            {{ scope.row.createdTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="loveCount" label="获赞数量" align="center" />
        <el-table-column prop="collectCount" label="收藏数量" align="center" />

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div style="display: flex; gap: 1px; justify-content: center">
              <el-button
                type="danger"
                style="padding: 5px 5px; font-size: 12px"
                @click="viewRoute(scope.row.id)"
                >查看路线</el-button
              >
              <el-button
                type="primary"
                style="padding: 5px 5px; font-size: 12px"
                @click="deletePost([scope.row.id])"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <span class="demonstration" />
        <div style="padding: 10px 0; text-align: center">
          <el-pagination
            @current-change="handelPageChange"
            :current-page="queryForm.pageNo"
            :page-size="queryForm.pageSize"
            :total="total"
            :page-count="pages"
            layout="total,prev,pager,next,jumper"
          >
          </el-pagination>
        </div>
      </div>
    </el-card>

    <!-- 地图弹框 -->
<!-- 地图弹框 -->
<el-dialog title="路线图" :visible.sync="mapVisible" width="80%">
  <div style="display: flex; flex-direction: row; gap: 20px;">
    <!-- 地图容器 -->
    <div id="mapContainer" style="flex: 2; width: 100%; height: 500px; border: 1px solid #ccc;"></div>

    <!-- 信息展示 -->
    <div style="flex: 1; overflow-y: auto; max-height: 500px;">
      <el-card shadow="always">
        <div style="text-align: center; margin-bottom: 20px;">
          <img
            :src="data.avatar"
            alt="用户头像"
            style="width: 100px; height: 100px; border-radius: 50%;"
          />
          <h3>{{ data.nickname }}</h3>
        </div>
        <p><strong>标题：</strong> {{ data.title }}</p>
        <p><strong>描述：</strong> {{ data.description }}</p>
        <p><strong>起点：</strong> {{ data.startRoute }}</p>
        <p><strong>终点：</strong> {{ data.endRoute }}</p>
        <p><strong>距离：</strong> {{ data.distance }} 米</p>
        <p><strong>游玩次数：</strong> {{ data.playCount }}</p>
        <p><strong>收藏数：</strong> {{ data.collectCount }}</p>
        <p><strong>点赞数：</strong> {{ data.loveCount }}</p>
        <p><strong>评论数：</strong> {{ data.commentCount }}</p>
        <p><strong>发布时间：</strong> {{ data.createdTime }}</p>
        <el-carousel interval="5000" arrow="always">
          <el-carousel-item
            v-for="(image, index) in data.imageList"
            :key="index"
          >
            <img :src="image" alt="图片" style="width: 100%; border-radius: 10px;" />
          </el-carousel-item>
        </el-carousel>
      </el-card>
    </div>
  </div>
  <template #footer>
    <el-button type="primary" @click="mapVisible = false">关闭</el-button>
  </template>
</el-dialog>

  </div>
</template>

<script>
import { getPostPage, deletePostByIds, getPostById } from "@/api/post";
import dayjs from "dayjs";
import punctuation from "@/assets/punctuation.png";
export default {
  data() {
    return {
      mapVisible: false, // 地图弹框显示控制
      // 地图的默认中心点经纬度
      data:{},
      locations: [],
      mapInstanceP: null,
      // 存储坐标点
      queryForm: {
        pageNo: 1,
        pageSize: 5,
        username: "",
        title: "",
      },
      postList: [],
      total: 0,
      pages: 0,
      selectedIds: [],
      polyline:[],
    };
  },
  methods: {
    async fetchPost() {
      try {
        const response = await getPostPage(this.queryForm);
        this.postList = response.data.list;
        this.total = Number(response.data.total);
        this.pages = Number(response.data.pages);
        console.info("list:", this.postList);
        console.info("total:", this.total);
        console.info("pages:", this.pages);
      } catch (error) {
        console.error("查询失败", error);
      }
    },
    handelPageChange(page) {
      this.queryForm.pageNo = page;
      this.fetchPost();
    },
    reset() {
      this.queryForm.username = "";
      this.queryForm.title = "";
      this.fetchPost();
    },
    async deletePost(ids) {
      try {
        await deletePostByIds(ids);
        this.$message.success("删除成功");
        if (this.postList.length <= ids.length && this.queryForm.pageNo > 1) {
          this.queryForm.pageNo -= 1;
        }
        this.fetchPost();
      } catch (error) {
        this.$message.error("删除失败" + (error.message || "未知错误"));
      }
    },
    async deleteSelected() {
      if (this.selectedIds.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      this.deletePost(this.selectedIds);
    },
    handelSelectionChange(selected) {
      this.selectedIds = selected.map((item) => item.id);
    },
    viewRoute(postId) {
      // 打开弹框
      this.mapVisible = true;
      getPostById(postId)
        .then((response) => {
          if (response && response.data) {
            console.log("Post data:", response.data); // 处理获取到的数据
            this.locations = response.data.route;
            this.polyline =  response.data.polyline;
            this.data = response.data;
            // 确保地图弹框渲染完成后初始化地图
            this.$nextTick(() => {
              this.initMap();
            });
          }
        })
        .catch((error) => {
          console.error("获取帖子数据失败:", error);
        });
    },
    initMap() {
      // 判断经纬度是否为合法数字
      const { latitude, longitude } = this.locations[0];
      if (isNaN(latitude) || isNaN(longitude)) {
        console.error("经纬度数据无效！");
        return;
      }
      // 如果地图实例已经存在，先销毁它
      if (this.mapInstanceP) {
        this.mapInstanceP.destroy();
      }
      // 创建地图实例并设置中心点和缩放级别
      // 初始化地图
      this.mapInstanceP = new TMap.Map("mapContainer", {
        center: new TMap.LatLng(latitude, longitude),
        zoom: 20,
      });

      // 创建多文本标注样式
      const labelStyle = new TMap.LabelStyle({
        color: "#0000FF", // 文字颜色
        size: 14, // 文字大小
        offset: { x: 0, y: 20 }, // 正值使文字在图标下方
        alignment: "center", // 水平居中对齐
        verticalAlignment: "middle", // 垂直居中对齐
      });

      // 创建文字标注数据
      const labelGeometries = this.locations.map((location, index) => {
        return {
          id: `label-${index}`, // 设置唯一ID
          styleId: "labelStyle", // 使用样式ID
          position: new TMap.LatLng(location.latitude, location.longitude),
  content: "地点" + (index + 1)  + "-" + location.name, // 每个标记下的文字内容

        };
      });

      // 创建点标记数据
      const markerGeometries = this.locations.map((location, index) => {
        return {
          id: `marker-${index}`, // 设置唯一ID
          styleId: "markerStyle", // 使用样式ID
          position: new TMap.LatLng(location.latitude, location.longitude),
        };
      });

      // 创建图标样式
      const markerStyle = new TMap.MarkerStyle({
        width: 25, // 图标宽度
        height: 25, // 图标高度
        src: punctuation, // 图标路径
        anchor: { x: 12.5, y: 12.5 }, // 焦点设置在图标中心
      });

      // 添加图标标记
      new TMap.MultiMarker({
        map: this.mapInstanceP,
        styles: {
          markerStyle, // 定义图标样式
        },
        geometries: markerGeometries, // 点标记数据
      });

      // 添加文字标注
      new TMap.MultiLabel({
        map: this.mapInstanceP,
        styles: {
          labelStyle, // 定义文字样式
        },
        geometries: labelGeometries, // 文字标注数据
      });

            // 转换点为腾讯地图 LatLng 对象
      const latLngPoints = this.polyline.map(
        (point) => new TMap.LatLng(point.latitude, point.longitude)
      );

      // 创建 MultiPolyline
      new TMap.MultiPolyline({
        id: "polyline-layer", // 图层ID
        map: this.mapInstanceP, // 显示在哪个地图实例中
        styles: {
          style1: new TMap.PolylineStyle({
            color: "#FF0000", // 线颜色
            width: 6, // 线宽度
            borderWidth: 1, // 边框宽度
            borderColor: "#000000", // 边框颜色
          }),
        },
        geometries: [
          {
            id: "line1", // 每条线的唯一标识
            styleId: "style1", // 使用的样式ID
            paths: latLngPoints, // 路径
          },
        ],
      });
      
    },
  },
  mounted() {
    this.fetchPost();
  },
  filters: {
    formatDate(value) {
      return value ? dayjs(value).format("YYYY-MM-DD HH:mm:ss") : "";
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.mll-5 {
  margin-left: 10px;
}
</style>